function p = bvqxtools_path(p)
% bvqxtools_path  - get path where BVQXtools is installed
%
% FORMAT:       p = bvqxtools_path([p])
%
% Input fields:
%
%       p           optional path, either of
%                   - base (default)
%                   - bin
%                   - colin
%                   - contrib
%                   - files (outside of BVQXtools)
%                   - lut
%                   - tfg
%
% Output fields:
%
%       p           path with forward slashes for BVQXfile (or other)

% Version:  v0.8a
% Build:    9102222
% Date:     Oct-22 2008, 10:22 PM CEST
% Author:   Jochen Weber, SCAN Unit, Columbia University, NYC, NY, USA
% URL/Info: http://wiki.brainvoyager.com/BVQXtools

% persistent memory
persistent bvqx_p;
if numel(bvqx_p) ~= 1 || ...
   ~isstruct(bvqx_p)

    % create struct
    bvqx_p = struct;
    
    % get path
    px = strrep(fileparts(mfilename('fullpath')), '\', '/');
    if px(end) == '/'
        px(end) = [];
    end
    
    % put path in base field
    bvqx_p.base = px;
    
    % get files folder
    [p1, p2] = fileparts(px);
    p2 = regexprep(p2, '^(.*_v\d+[a-z]*).*$', '$1_files');
    p2 = [p1 '/' p2];
    bvqx_p.files = p2;
    
    % other folders
    bvqx_p.bin     = [p2 '/bin/' strrep(mexext, 'mex', '')];
    bvqx_p.colin   = [p2 '/colin'];
    bvqx_p.contrib = [p2 '/contrib'];
    bvqx_p.dicom   = [p2 '/dicom'];
    bvqx_p.icons   = [p2 '/images/icons'];
    bvqx_p.ihc     = [p2 '/ihc'];
    bvqx_p.images  = [p2 '/images'];
    bvqx_p.lut     = [p2 '/lut'];
    bvqx_p.srf     = [p2 '/srf'];
    bvqx_p.tal     = [p2 '/tal'];
    bvqx_p.tfg     = [p2 '/tfg'];
end

% argument check
if nargin < 1
    p = 'base';
elseif ~ischar(p) || ...
    isempty(p)
    error( ...
        'BVQXtools:BadArgument', ...
        'Invalid p argument.' ...
    );
else
    p = lower(p(:)');
end

% pre-set
if isfield(bvqx_p, p)
    p = bvqx_p.(p);
    return;
end

% found in files
if exist([bvqx_p.files '/' p], 'dir') > 0
    p = [bvqx_p.files '/' p];
    
% else return base path
else
    warning( ...
        'BVQXtools:BadArgument', ...
        'Invalid pathspec: %s, returning base dir.', ...
        p ...
    );
    p = bvqx_p.base;
end
